package com.copro.chemdb.utils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import org.ihelpuoo.db.sql.SQLSegment;
import org.ihelpuoo.parser.segment.SegmentUtils;

import com.copro.chemdb.beans.Account;
import com.copro.simple.Application;
import com.copro.simple.SimpleException;
import com.copro.simple.db.QueryCallback;

public class AccountUtils {

	static class AccountGetter implements QueryCallback {

		private Account account;

		public AccountGetter() {
		}

		public Account getObject() {
			return this.account;
		}

		@Override
		public void exec(ResultSet rs) throws SQLException {
			if (rs.first())
				this.account = new Account(rs);

		}

	}

	static class AccountListGetter implements QueryCallback {

		private List<Account> list;

		public AccountListGetter(List<Account> list) {
			this.list = list;
		}

		public List<Account> getList() {
			return this.list;
		}

		@Override
		public void exec(ResultSet rs) throws SQLException {
			while (rs.next()) {
				list.add(new Account(rs));
			}
		}
	}

	public static Account getAccountByName(Application app, String name)
			throws SimpleException {
		SQLSegment sql = app.getSQL("getAccount");
		sql.set("name", name);
		AccountGetter callback = new AccountGetter();
		app.query(sql.toString(), callback);
		return callback.getObject();
	}

	public static List<Account> getAllAccounts(Application app)
			throws SimpleException {
		AccountListGetter callback = new AccountListGetter(
				new LinkedList<Account>());
		SQLSegment sql = app.getSQL("getAllAccount");
		app.query(sql.toString(), callback);
		return callback.getList();
	}

	public static void deleteAccount(Application app, String name)
			throws SimpleException {
		SQLSegment sql = app.getSQL("deleteAccount");
		sql.set("name", name);
		app.exec(sql.toString());
	}

	public static void addAccount(Application app, Account account)
			throws SimpleException {
		SQLSegment sql = app.getSQL("addAccount");
		SegmentUtils.fillByObject(sql, account);
		app.exec(sql.toString());
	}

	public static void updateAccount(Application app, Account account)
			throws SimpleException {
		SQLSegment sql = app.getSQL("updateAccount");
		SegmentUtils.fillByObject(sql, account);
		app.exec(sql.toString());
	}
}
